package com.guguskins.back.common.helper;

import com.alibaba.fastjson.JSONObject;
import com.guguskins.back.entity.GuPermission;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 根据权限数据构建登录用户左侧菜单数据
 * </p>
 *
 * @author qy
 * @since 2019-11-11
 */
public class MenuHelper {

    /**
     * 构建菜单
     *
     * @param treeNodes
     * @return
     */
    public static List<JSONObject> build(List<GuPermission> treeNodes) {
        List<JSONObject> menus = new ArrayList<>();
        /*if(treeNodes.size() == 1) {
            HuiPermissionEntity topNode = treeNodes.get(0);
            //左侧一级菜单
            List<HuiPermissionEntity> oneMenuList = topNode.getChildren();*/
        for (GuPermission one : treeNodes) {
            JSONObject oneMenu = new JSONObject();
            oneMenu.put("key", one.getPath());
//            oneMenu.put("component", one.getComponent());
            oneMenu.put("title", one.getTitle());
            oneMenu.put("icon", one.getIcon());

            List<JSONObject> children = new ArrayList<>();
            List<GuPermission> twoMenuList = one.getChildren();
            for (GuPermission two : twoMenuList) {
                subMenu(children, two);
                List<GuPermission> threeMenuList = two.getChildren();
                for (GuPermission three : threeMenuList) {
                    if (StringUtils.isEmpty(three.getPath())) {
                        continue;
                    }
                    subMenu(children, three);
                }
            }
            if (!CollectionUtils.isEmpty(children)) {
                oneMenu.put("children", children);
            }
            menus.add(oneMenu);
        }
        return menus;
}

    private static void subMenu(List<JSONObject> children, GuPermission sub) {
        JSONObject threeMenu = new JSONObject();
        threeMenu.put("key", sub.getPath());
//        threeMenu.put("component", sub.getComponent());
        threeMenu.put("title", sub.getTitle());
        threeMenu.put("icon", sub.getIcon());
        children.add(threeMenu);
    }
}
